#!/usr/bin/env python
#
# Copyright 2009 Benjamin Davis
#
# This file is part of resistencia.
#
# resistencia is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# resistencia is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with resistencia.  If not, see <http://www.gnu.org/licenses/>.

import os.path
import shelve

from mud.options import *

def load(name):
    """Loads a dungeon from the file and returns it.
    If no dungeon exists, return None"""
    # If storage directory doesn't exist
    try:
        # Create it (and parents) 
        os.makedirs(SAVE_PREFIX)
    except OSError:
        pass
    # Open storage file
    d = shelve.open(os.path.join(SAVE_PREFIX, 'data'))
    try:
        # Load dungeon from file
        dungeon = d[name]
    except KeyError:
        # Unless it doesn't exist, return None
        dungeon = None
    # Close storage file
    d.close()
    return dungeon

def save(name, dungeon):
    """Saves a dungeon to file and returns True upon success,
    but False upon failure"""
    # Open storage file
    d = shelve.open(os.path.join(SAVE_PREFIX, 'data'))
    try:
        # Save dungeon to file
        d[name] = dungeon
        ret = True
    except:
        # Upon error, return False
        ret = False
    # Close storage file
    d.close()
    return ret
